package cn.itcast.controller;

import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2018/5/11.
 */
//用户控制器
@Controller("userController")
public class UserController {

    @Autowired
    private UserService userService;

    //用户通过get访问
    @RequestMapping(value = "/login.action", method = RequestMethod.GET)
    public String login(HttpSession session){

//        session.invalidate();

        return "login";
    }

    //用户通过get访问
    @RequestMapping(value = "/tologin.action")
    public String logins(){

        return "customer";
    }

    //用户通过登入访问
    @RequestMapping(value = "/login.action", method = RequestMethod.POST)
    public String tologin(String usercode, String password, Model model, HttpSession session){
        System.out.println(usercode);
        User user = userService.findUser(usercode,password);

        if(user!=null){
            //将用户添加到session
            session.setAttribute("USER_SESSION",user);
            //跳转到主页
            return "redirect:customer/list.action";
        }else {
            model.addAttribute("msg","用户名或密码错误请重新登入");
            //返回登入页面
            return "login";
        }
    }

    //退出登入
    @RequestMapping("/logout.action")
    public String LoginOut(HttpSession session){

        //清楚用户在session中的信息
        session.invalidate();

        //重定向退出到登入页面
        return "redirect:login.action";
    }
}
